package com.example.newbook.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import okhttp3.*;

/**
 * @program: littleRedBook240509
 * @author: tenghw
 * @create: 2024-05-10 17:54
 * @Version 1.0
 * @description:
 **/
//@RestController
//@Slf4j
public class SendWeixinController {

    /**
     * 跳转的小程序页面
     */
    //private static final String PAGES_ZP = "pages/draft-review/list/list";

    private static final String appId = "wxdd518bb7e604f65f";// 不用改
    private static final String appSecret = "3cf5e4cffdbc31eb8dfad0cbcd501419";// 不用改
    //private static final String openId = "ou5gu60OisDZYg-nNciXTuXo4q5o";
    private static final String openId = "ou5gu65JM1v6v_C4TbxZyPgRF9Ns";// 换成该用户的openId
    private static final String templateId = "-X9K2LRucCam5X3DazylB4voMADggHLp1wB67MYwyuI";// 不用改

    // OkHttp请求微信
    private static final OkHttpClient CLIENT = new OkHttpClient();
    //@GetMapping("/api/wx")
    public  void sendTemplateMessage(String title) {
        try {
            // Step 1: 获取access_token
            String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            Request accessTokenRequest = new Request.Builder().url(accessTokenUrl).build();
            Response accessTokenResponse = CLIENT.newCall(accessTokenRequest).execute();
            String responseBody = accessTokenResponse.body().string();
            //JSONObject accessTokenJson = new JSONObject(responseBody);
            JSONObject accessTokenJson = JSONObject.parseObject(responseBody);
            String accessToken = accessTokenJson.getString("access_token");

            // Step 2: 构建消息体并发送
            String messageUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            // 对应模版中的消息
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd");
            JSONObject miniprogram = new JSONObject();
            miniprogram.put("platform", new JSONObject().fluentPut("value", "小红书").fluentPut("color", "#d51a1d"));
            miniprogram.put("who", new JSONObject().fluentPut("value", "应子冬").fluentPut("color", "#173177"));
            miniprogram.put("datetime", new JSONObject().fluentPut("value", currentDate.format(formatter2)).fluentPut("color", "#173177"));
            miniprogram.put("title", new JSONObject().fluentPut("value", title).fluentPut("color", "#173177"));

            JSONObject messageData = new JSONObject();
            // 设置消息类型为模板消息
            //messageData.put("msgtype", "template");
            messageData.put("touser", openId);
            messageData.put("template_id", templateId);
            messageData.put("data", miniprogram);

            //System.out.println(messageData.toJSONString()+">>>>>>>11111111111111");
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), messageData.toJSONString());
            Request messageRequest = new Request.Builder().url(messageUrl).post(requestBody).build();
            Response messageResponse = CLIENT.newCall(messageRequest).execute();
            System.out.println("-------------------------------------------------------------------");
            if (messageResponse.isSuccessful()) {
                System.out.println("消息发送成功！");
                System.out.println("发送给微信公众号或微信小程序后的响应: " + messageResponse.body().string());
            } else {
                String errMsg = messageResponse.body().string();
                System.err.println("消息发送失败，错误信息：" + errMsg);
            }
            System.out.println("-------------------------------------------------------------------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 读取一个json文件中某个key的值
    public  String  readJsonKey(String desktopPath,String keyToFind) throws IOException {
        String filePath = desktopPath + File.separator + "redbok.json";
        if(StringUtils.isEmpty(keyToFind)){
            return "";
        }
        // 使用FileReader和BufferedReader读取文件内容
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
        reader.close();
        // 将文件内容转换为JSONObject
        JSONObject jsonObject = JSON.parseObject(content.toString());

        // 获取键对应的值
        Object value= jsonObject.get(keyToFind);

        if (value != null) {
            // 打印键值
            System.out.println("Value of key '" + keyToFind + "' is: " + value);
            return value.toString();
        } else {
            System.out.println("Key '" + keyToFind + "' not found in the redbok.json");
            return "noKey";
        }
    }
}